package com.mrdeer.web.service.sys.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.dfa.WordTree;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mrdeer.common.entity.beans.PageEntity;
import com.mrdeer.common.entity.dto.StopWordDTO;
import com.mrdeer.common.entity.sys.StopWord;
import com.mrdeer.common.exception.BusinessException;
import com.mrdeer.web.mapper.StopWordMapper;
import com.mrdeer.web.service.sys.SysStopWordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Slf4j
@Service
@Transactional
public class SysStopWordServiceImpl extends ServiceImpl<StopWordMapper, StopWord> implements SysStopWordService {

    @Resource
    private StopWordMapper stopWordMapper;

    private static WordTree wordTree;

    public WordTree getInstance() {
        if (wordTree == null) {
            //初始加载数据
            wordTree = new WordTree();
            stopWordMapper.selectList(null).forEach(e -> wordTree.addWord(e.getTitle()));
        }
        return wordTree;
    }

    @Override
    public StopWord add(StopWord stopWord) {
        if (stopWordMapper.insert(stopWord) > 0) {
            return stopWordMapper.selectById(stopWord.getId());
        }
        throw new BusinessException("add failed");
    }

    @Override
    public boolean delete(String id) {
        StopWord stopWord = getById(id);
        if (null == stopWord) {
            throw new BusinessException("the stopWord does not exist");
        }
        return stopWordMapper.deleteById(id) > 0;
    }

    @Override
    public StopWord update(StopWord stopWord) {
        if (stopWordMapper.updateById(stopWord) > 0) {
            StopWord select = stopWordMapper.selectById(stopWord.getId());
            return select;
        }
        throw new BusinessException("update failed");
    }

    @Override
    public StopWord getById(String id) {
        return stopWordMapper.selectById(id);
    }

    @Override
    public Page<StopWord> list(StopWordDTO dto) {
        if (null == dto.getPage()) {
            dto.setPage(new PageEntity());
        }
        return stopWordMapper.selectPage(dto.getPage().convert(), fuzzyQuery(dto));
    }

    @Override
    public LambdaQueryWrapper<StopWord> fuzzyQuery(StopWordDTO dto) {
        LambdaQueryWrapper<StopWord> queryWrapper = Wrappers.<StopWord>query().lambda();
        if (null != dto) {
            if (StrUtil.isNotBlank(dto.getTitle())) {
                queryWrapper.like(StopWord::getTitle, dto.getTitle());
            }
        }
        return queryWrapper;
    }
}
